//
//  PBJViewController.m
//  TestVideo
//
//  Created by Wang Xj on 13-8-29.
//  Copyright (c) 2013年 Xj Wang. All rights reserved.
//

#import "PBJViewController.h"
#import "BanBu_AppDelegate.h"
#import "TKLoadingView.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "UIViewController+Animation.h"
#import "BanBu_SnapController.h"

@interface PBJViewController ()

@end

@implementation PBJViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _assetLibrary = [[ALAssetsLibrary alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor blackColor];
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    _progress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
    [_progress setFrame:CGRectMake(10, 84, 260, 35)];
    _progress.progress = 0;
    [self.view addSubview:_progress];
    
    _timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(280, 70, 40, 35)];
    _timeLabel.backgroundColor = [UIColor clearColor];
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.font = [UIFont systemFontOfSize:17];
    _timeLabel.text = @"00\"";
    [self.view addSubview:_timeLabel];
    
    CGFloat viewWidth = CGRectGetWidth(self.view.frame);
    
    _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancelButton.frame = CGRectMake(viewWidth - 120.0f, 15.0f, 50.0f, 50.0f);
    [_cancelButton setBackgroundImage:[UIImage imageNamed:@"blog_post_filter_recapture_norm@2x.png"] forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(cancelRecord:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cancelButton];
    
    _videoAndPhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _videoAndPhotoButton.frame = CGRectMake(84, 25, 49, 30);
    _videoAndPhotoButton.hidden = YES;
    [_videoAndPhotoButton setBackgroundImage:[UIImage imageNamed:@"camera-change.png"] forState:UIControlStateNormal];
    [_videoAndPhotoButton addTarget:self action:@selector(exchangeVideoAndPhoto:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_videoAndPhotoButton];
    
    // done button
    _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _doneButton.frame = CGRectMake(viewWidth - 70.0f, 15.0f, 50.0f, 50.0f);
    UIImage *buttonImage = [UIImage imageNamed:@"blog_post_filter_apply_norm@2x.png"];
    [_doneButton setImage:buttonImage forState:UIControlStateNormal];
    [_doneButton addTarget:self action:@selector(_handleDoneButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_doneButton];
    
    // elapsed time and red dot
    _strobeView = [[PBJStrobeView alloc] initWithFrame:CGRectZero];
    CGRect strobeFrame = _strobeView.frame;
    strobeFrame.origin = CGPointMake(15.0f, 25.0f);
    _strobeView.frame = strobeFrame;
    _strobeView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_strobeView];
    
    // preview
    _previewView = [[UIView alloc] initWithFrame:CGRectZero];
    _previewView.backgroundColor = [UIColor blackColor];
    CGRect previewFrame = CGRectZero;
    previewFrame.origin = CGPointMake(0, 150.0f);
    
    CGFloat previewWidth = self.view.frame.size.width;
    previewFrame.size = CGSizeMake(previewWidth, 240);
    _previewView.frame = previewFrame;
    
    
    // add AV layer
    _previewLayer = [[PBJVision sharedInstance] previewLayer];
    CGRect previewBounds = _previewView.layer.bounds;
    _previewLayer.bounds = previewBounds;
    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _previewLayer.position = CGPointMake(CGRectGetMidX(previewBounds), CGRectGetMidY(previewBounds));
    [_previewView.layer addSublayer:_previewLayer];
    [self.view addSubview:_previewView];
    
    // press to record gesture
    _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] init];
    _longPressGestureRecognizer.delegate = self;
    _longPressGestureRecognizer.minimumPressDuration = 0.05f;
    _longPressGestureRecognizer.allowableMovement = 10.0f;
    [_longPressGestureRecognizer addTarget:self action:@selector(_handleLongPressGestureRecognizer:)];
    
    // gesture view to record
    UIView *gestureView = [[UIView alloc] initWithFrame:CGRectZero];
    CGRect gestureFrame = self.view.bounds;
    gestureFrame.origin = CGPointMake(0, 60.0f);
    gestureFrame.size.height -= 10.0f;
    gestureView.frame = gestureFrame;
    [self.view addSubview:gestureView];
    [gestureView addGestureRecognizer:_longPressGestureRecognizer];
    
    // flip button
    _flipButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    UIImage *flipImage = [UIImage imageNamed:@"capture_flip@2x.png"];
    [_flipButton setBackgroundImage:flipImage forState:UIControlStateNormal];
    
    CGRect flipFrame = _flipButton.frame;
    flipFrame.size = CGSizeMake(60.0f, 60.0f);
    flipFrame.origin = CGPointMake(10.0f, CGRectGetHeight(self.view.bounds) - 60.0f);
    _flipButton.frame = flipFrame;
    
    [_flipButton addTarget:self action:@selector(_handleFlipButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_flipButton];
    
    
    //闪光灯
    _torchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_torchButton setBackgroundImage:[UIImage imageNamed:@"torch.png"] forState:UIControlStateNormal];
    _torchButton.frame = CGRectMake(90, CGRectGetHeight(self.view.bounds) - 60.0f, 60, 60);
    [_torchButton addTarget:self action:@selector(torchButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_torchButton];
    _torchON = NO;
    
    //静音
    _muteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *muteImage = [UIImage imageNamed:@"notMute.png"];
    [_muteButton setBackgroundImage:muteImage forState:UIControlStateNormal];
    
    CGRect muteFrame = _flipButton.frame;
    muteFrame.size = CGSizeMake(60.0f, 60.0f);
    muteFrame.origin = CGPointMake(170.0f, CGRectGetHeight(self.view.bounds) - 60.0f);
    _muteButton.frame = muteFrame;
    
    [_muteButton addTarget:self action:@selector(setMute:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_muteButton];
    
    //视频尺寸
    _definitionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage * definitionImage = [UIImage imageNamed:@"rectangle.png"];
    [_definitionButton setBackgroundImage:definitionImage forState:UIControlStateNormal];
    
    CGRect definitionFrame = _flipButton.frame;
    definitionFrame.size = CGSizeMake(60.0f, 60.0f);
    definitionFrame.origin = CGPointMake(250.0f, CGRectGetHeight(self.view.bounds) - 60.0f);
    _definitionButton.frame = definitionFrame;
    
    [_definitionButton addTarget:self action:@selector(setDefinition:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_definitionButton];
    
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"longPressToVideo", nil) activityAnimated:NO duration:1.3];
    
    if (__MainScreen_Height < 500)//3.5寸,需要重新布局
    {
        _strobeView.frame = CGRectMake(15, 10, 0, 0);
        _cancelButton.frame = CGRectMake(viewWidth - 120.0f, 2.0f, 50.0f, 50.0f);
        _doneButton.frame = CGRectMake(viewWidth - 70.0f, 2.0f, 50.0f, 50.0f);
        _videoAndPhotoButton.frame = CGRectMake(84, 15, 49, 30);
        [_progress setFrame:CGRectMake(10, 64, 260, 35)];
        [_timeLabel setFrame:CGRectMake(280, 50, 40, 35)];
        [_previewView setFrame:CGRectMake(0, 110, self.view.frame.size.width, 240)];
    }
    
    PBJVision *vision = [PBJVision sharedInstance];
    vision.squareOrRectangle = NO;
    if(IS_IOS_7)
    {
        [vision setCameraDevice:PBJCameraDeviceFront];
    }
    
    self.count = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(playDefinitionButton) userInfo:nil
                                    repeats:YES];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     MyAppDataManager.recordingVideo = YES; //录制视频
    self.navigationController.navigationBarHidden = YES;
    
    _timeLabel.text = @"00\"";

    [self _resetCapture];
    [[PBJVision sharedInstance] startPreview];
    if ([self.quote isEqualToString:@"snap"])
    {
        _videoAndPhotoButton.hidden = NO;
//        _cancelButton.hidden = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    MyAppDataManager.recordingVideo = NO;//结束录制视频
    
    _flipButton.enabled = YES;
    _torchButton.enabled = YES;
    _muteButton.enabled = YES;
    _definitionButton.enabled = YES;
    
    self.navigationController.navigationBarHidden = NO;
    [super viewWillDisappear:animated];
    
    [[PBJVision sharedInstance] stopPreview];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//进来时先播放动画
-(void)playDefinitionButton
{
    if (self.count>6)
    {
        UIImage * rectangleImage = [UIImage imageNamed:@"rectangle.png"];
        [_definitionButton setBackgroundImage:rectangleImage forState:UIControlStateNormal];
        if([self.timer isValid])
        {
            [self.timer invalidate];
            self.timer = nil;
        }
        return;
    }
    if (self.count%2)
    {
        UIImage * squareImage = [UIImage imageNamed:@"rectangle_shadow.png"];
        [_definitionButton setBackgroundImage:squareImage forState:UIControlStateNormal];
    }
    else
    {   UIImage * rectangleImage = [UIImage imageNamed:@"rectangle.png"];
        [_definitionButton setBackgroundImage:rectangleImage forState:UIControlStateNormal];
    }
    self.count ++;
}

#pragma mark - private start/stop helper methods

- (void)_startCapture
{
    [UIApplication sharedApplication].idleTimerDisabled = YES;

    [[PBJVision sharedInstance] startVideoCapture];
}

- (void)_pauseCapture
{
    [[PBJVision sharedInstance] pauseVideoCapture];
}

- (void)_resumeCapture
{
    [[PBJVision sharedInstance] resumeVideoCapture];
}

- (void)_endCapture
{
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    [[PBJVision sharedInstance] endVideoCapture];
}

- (void)_resetCapture
{
    [_strobeView stop];
    _longPressGestureRecognizer.enabled = YES;
    
    PBJVision *vision = [PBJVision sharedInstance];
    vision.delegate = self;
    [vision setCameraMode:PBJCameraModeVideo];
    
    //前置摄像头
    BOOL isCameraFront = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    //后置摄像头
    BOOL isCameraRear = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    
    if (self.quote.length)
    {
        if (isCameraRear)
        {
            [vision setCameraDevice:PBJCameraDeviceBack];
        }
        else if (isCameraFront)
        {
            [vision setCameraDevice:PBJCameraDeviceFront];
        }
    }
    else
    {
        if (isCameraFront)
        {
            [vision setCameraDevice:PBJCameraDeviceFront];
        }
        else
        {
            [vision setCameraDevice:PBJCameraDeviceBack];
        }
    }
    [vision setCameraOrientation:PBJCameraOrientationPortrait];
    [vision setFocusMode:PBJFocusModeAutoFocus];
}

#pragma mark - UIButton

- (void)_handleFlipButton:(UIButton *)button
{
    PBJVision *vision = [PBJVision sharedInstance];
    
    if (vision.cameraDevice == PBJCameraDeviceBack)
    {
        BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
        if (!isCamera)
        {
            return;//前置摄像头不可用
        }
        [vision setCameraDevice:PBJCameraDeviceFront];
    }
    else
    {
        BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
        if (!isCamera)
        {
            return;//后置摄像头不可用
        }
        [vision setCameraDevice:PBJCameraDeviceBack];
    }
}

- (void)_handleDoneButton:(UIButton *)button
{
    // resets long press
    _longPressGestureRecognizer.enabled = NO;
    _longPressGestureRecognizer.enabled = YES;
    
    //保存视频
    _isSave = YES;

    [self _endCapture];
    
    if ([self.quote isEqualToString:@"snap"])
    {
        [self.navigationController dismissViewControllerAnimated:YES];
    }
    else
    {
        [self dismissViewControllerAnimated:YES];
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1001)
    {
        switch (buttonIndex)
        {
            case 0:
                break;
            case 1://保存视频
            {
                _isSave = YES;
                [self _endCapture];
            }
                break;
            default:
                break;
        }
    }
    else
    {
        [self _resetCapture];
    }
}

#pragma mark - UIGestureRecognizer

- (void)_handleLongPressGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
    [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:0];
    
    switch (gestureRecognizer.state)
    {
        case UIGestureRecognizerStateBegan:
        {
            if (!_recording)
            {
                _flipButton.enabled = NO;
                _torchButton.enabled = NO;
                _muteButton.enabled = NO;
                _definitionButton.enabled = NO;
                [self _startCapture];
            }
            else
                [self _resumeCapture];
            break;
        }
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateFailed:
        {
            [self _pauseCapture];
            break;
        }
        default:
            break;
    }
}

#pragma mark - PBJVisionDelegate

- (void)visionPreviewDidStart:(PBJVision *)vision
{
    _longPressGestureRecognizer.enabled = YES;
}

- (void)visionPreviewWillStop:(PBJVision *)vision
{
    _longPressGestureRecognizer.enabled = NO;
}

// video capture

- (void)visionDidStartVideoCapture:(PBJVision *)vision
{
    [_strobeView start];
    _recording = YES;
}

- (void)visionDidPauseVideoCapture:(PBJVision *)vision
{
    [_strobeView stop];
}

- (void)visionDidResumeVideoCapture:(PBJVision *)vision
{
    [_strobeView start];
}

#pragma mark - 保存视频、发送
//保存录制的视频
- (void)vision:(PBJVision *)vision capturedVideo:(NSDictionary *)videoDict error:(NSError *)error
{
    if (!_isSave)
    {
        return;
    }
    _recording = NO;
    
    if (error) {
        return;
    }
    
    _currentVideo = videoDict;

    NSString *videoPath = [_currentVideo  objectForKey:PBJVisionVideoPathKey];
    
    [_assetLibrary writeVideoAtPathToSavedPhotosAlbum:[NSURL URLWithString:videoPath] completionBlock:^(NSURL *assetURL, NSError *error1)
     {
         MPMoviePlayerController * movieController= [[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:videoPath]];
    
         UIImage * image = [movieController thumbnailImageAtTime:0.1 timeOption:MPMovieTimeOptionNearestKeyFrame];
         [movieController stop];
         NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
         [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
         
         NSString * videoName = [NSString stringWithFormat:@"%@_%@",[formatter stringFromDate:[NSDate date]],MyAppDataManager.useruid];
         
         [self saveToVideoAlbum:videoPath videoName:videoName imgae:image];
//         [formatter release];
//         [movieController release];
         
         [self cancelRecord:nil];
         
     }];
}

//保存视频、缩略图到半圆相册 ,并发送
-(void)saveToVideoAlbum:(NSString *)videoPath videoName:(NSString *)videoName imgae:(UIImage *)image
{
    //缩略图
    //保存文件到半圆相册
    NSString * cacheFile = [AppComManager pathForVideoAlbumMedia:videoName];
    
    NSData * data = UIImageJPEGRepresentation(image, 0.5);
    [data writeToFile:[NSString stringWithFormat:@"%@.jpg",cacheFile] atomically:YES];
        
    //视频
    [FileManager copyItemAtPath:videoPath toPath:[NSString stringWithFormat:@"%@.mp4",cacheFile] error:nil];
    
    NSString * videoFilePath = [[[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"]stringByAppendingPathComponent:@"AlbumFolder"]stringByAppendingPathComponent:@"videoInfo.plist"];
    
    NSMutableDictionary * videoDic = [NSMutableDictionary dictionaryWithCapacity:5];
    [videoDic setValue:videoName forKey:@"video"];
    [videoDic setValue:[NSString stringWithFormat:@"%@.mp4",cacheFile] forKey:@"videoName"];
    [videoDic setValue:[NSString stringWithFormat:@"%@.jpg",cacheFile] forKey:@"thumbnailName"];
    
    NSMutableArray * arr = [NSMutableArray arrayWithCapacity:10];
    if([FileManager fileExistsAtPath:videoFilePath])
    {
        arr = [NSMutableArray arrayWithContentsOfFile:videoFilePath];
    }
    
    [arr addObject:videoDic];
    [arr writeToFile:videoFilePath atomically:YES];
        
    
    //发送消息
    NSMutableDictionary * sendDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:videoName,@"video",videoName,@"snapVideo",[NSNumber numberWithInt:ChatCellTypeVideo],KeyType, nil];

    if ([self.quote isEqualToString:@"snap"])
    {
        [sendDic setValue:@"snap" forKey:KeyShowFrom];
        [[NSNotificationCenter defaultCenter]postNotificationName:kSendMsgAllTypeNotification object:sendDic];
    }
    else
    {
        [sendDic setValue:@"mo" forKey:KeyShowFrom];
        [[NSNotificationCenter defaultCenter]postNotificationName:kSendMsgAllTypeNotification object:sendDic];
    }

    [[NSNotificationCenter defaultCenter]postNotificationName:@"addMediaToAlbum" object:sendDic];
    
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"saveToAlum", nil) activityAnimated:YES duration:1.5];
}

-(void)setProgressCus:(float)progress
{
    progress = fabsf(progress);
    _timeLabel.text = [NSString stringWithFormat:@"%02d\"",(int)progress];
    
    if ([self.quote isEqualToString:@"snap"])
    {
        progress = progress/9; //视频限制在9s;
    }
    else
    {
        progress = progress/15; //视频限制在15s;
    }
    if (progress>=1)
    {
        [self _pauseCapture];
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"finishRecord", nil) activityAnimated:NO duration:1.2];
    }
    [_progress setProgress:progress animated:YES];
    
}
-(void)torchButtonClick:(UIButton *)sender
{
    _torchON = !_torchON;
    [self torchOn:_torchON];
}

-(void)torchOn:(BOOL)on
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch])
    {
        [device lockForConfiguration:nil];
        if (on)
        {
            [device setTorchMode: AVCaptureTorchModeOn];
        }
        else
        {
            [device setTorchMode: AVCaptureTorchModeOff];
        }
        
        [device unlockForConfiguration];
    }
}

//取消视频
-(void)cancelRecord:(UIButton *)sender
{
    {
        _isSave = NO;//不保存视频
        [self dismissViewControllerAnimated:YES];
    }
}

//设置静音
-(void)setMute:(UIButton *)sender
{
    [PBJVision sharedInstance].saveAudio = ![PBJVision sharedInstance].saveAudio;
    if ([PBJVision sharedInstance].saveAudio)
    {
        [sender setBackgroundImage:[UIImage imageNamed:@"notMute.png"] forState:UIControlStateNormal];
    }
    else
    {
        [sender setBackgroundImage:[UIImage imageNamed:@"mute.png"] forState:UIControlStateNormal];
    }
}

//设置视频尺寸
-(void)setDefinition:(UIButton *)sender
{
    [PBJVision sharedInstance].squareOrRectangle = ![PBJVision sharedInstance].squareOrRectangle;
    if ([PBJVision sharedInstance].squareOrRectangle)
    {//正方形
        [self setVideoFrame:@"square"];
        [sender setBackgroundImage:[UIImage imageNamed:@"square.png"] forState:UIControlStateNormal];
    }
    else
    {
        [self setVideoFrame:@"rectangle"];
        [sender setBackgroundImage:[UIImage imageNamed:@"rectangle.png"] forState:UIControlStateNormal];
    }
}

-(void)setVideoFrame:(NSString *)shape
{
    if([self.timer isValid])
    {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    if ([shape isEqualToString:@"rectangle"])
    {
        CGRect previewFrame = CGRectZero;
        previewFrame.origin = CGPointMake(0, 150.0f);
        
        CGFloat previewWidth = self.view.frame.size.width;
        previewFrame.size = CGSizeMake(previewWidth, 240);
        _previewView.frame = previewFrame;
        
        if (__MainScreen_Height < 500)
        {
            [_previewView setFrame:CGRectMake(0, 110, self.view.frame.size.width, 240)];
        }
        
        CGRect previewBounds = _previewView.layer.bounds;
        _previewLayer.bounds = previewBounds;
        _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _previewLayer.position = CGPointMake(CGRectGetMidX(previewBounds), CGRectGetMidY(previewBounds));
        [_previewView.layer addSublayer:_previewLayer];
    }
    else
    {
        CGRect previewFrame = CGRectZero;
        previewFrame.origin = CGPointMake(0, 120.0f);
        
        CGFloat previewWidth = self.view.frame.size.width;
        previewFrame.size = CGSizeMake(previewWidth, previewWidth);
        _previewView.frame = previewFrame;
        
        if (__MainScreen_Height < 500)
        {
            [_previewView setFrame:CGRectMake(0, 90, self.view.frame.size.width, previewWidth)];
        }
        
        CGRect previewBounds = _previewView.layer.bounds;
        _previewLayer.bounds = previewBounds;
        _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _previewLayer.position = CGPointMake(CGRectGetMidX(previewBounds), CGRectGetMidY(previewBounds));
        [_previewView.layer addSublayer:_previewLayer];
    }
}

- (void)exchangeVideoAndPhoto:(UIButton *)sender
{
    //切换为拍视频，按钮显示为photo
    [self.navigationController popViewControllerAnimated:NO];
}

/*
-(void)addPhotoFrameToVideo:(NSString *)filePath
{
    UIImage * iconImage = [UIImage imageNamed:@"video_mask_cctv.png"];
    CGPoint point = CGPointMake(0, 140);
    
    for(int i =0 ;i <[PBJVision sharedInstance].imageArray.count; i++)
    {
        NSData * data = [[PBJVision sharedInstance].imageArray objectAtIndex:i];
        UIImage * image = [UIImage imageWithData:data];
  
        image = [UIImage imageWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationUp];
        
        image = [PBJViewController addTwoImageToOne:image twoImage:iconImage topleft:point];
    
        data = UIImageJPEGRepresentation(image, 1);

        [[PBJVision sharedInstance].imageArray replaceObjectAtIndex:i withObject:data];
        data =[[PBJVision sharedInstance].imageArray objectAtIndex:i];
    }

    CGSize size = CGSizeMake(480, 640);
    [self writeImages:[PBJVision sharedInstance].imageArray ToMovieAtPath:filePath withSize:size inDuration:[PBJVision sharedInstance].imageArray.count/10.0 byFPS:10];
}


+ (UIImage *)addTwoImageToOne:(UIImage *)oneImg twoImage:(UIImage *)twoImg topleft:(CGPoint)tlPos
{
    UIGraphicsBeginImageContext(oneImg.size);
    [oneImg drawInRect:CGRectMake(0, 0, oneImg.size.width, oneImg.size.height)];
    [twoImg drawInRect:CGRectMake(tlPos.x, tlPos.y, 480, 640)];
    
    UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resultImg;
}

//转化为像素帧
- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image andSize:(CGSize) size
{
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
                             nil];
    CVPixelBufferRef pxbuffer = NULL;
    
    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, size.width,size.height, kCVPixelFormatType_32ARGB,(CFDictionaryRef) options,&pxbuffer);
    
    NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);
    
    CVPixelBufferLockBaseAddress(pxbuffer, 0);
    void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
    NSParameterAssert(pxdata != NULL);
    
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pxdata, size.width,
                                                 size.height, 8, 4*size.width, rgbColorSpace,
                                                 6);
    NSParameterAssert(context);
    CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
    CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),CGImageGetHeight(image)), image);
    CGColorSpaceRelease(rgbColorSpace);
    CGContextRelease(context);
    
    CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
    
    return pxbuffer;
}

//压缩成视频
- (void) writeImages:(NSArray *)imagesArray ToMovieAtPath:(NSString *) path withSize:(CGSize) size
          inDuration:(float)duration byFPS:(int32_t)fps
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:path])
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    //在这里将之前截取的图片合并成一个视频
    //Wire the writer:
    NSError *error = nil;
    AVAssetWriter *videoWriter = [[[AVAssetWriter alloc] initWithURL:[NSURL fileURLWithPath:path]fileType:AVFileTypeMPEG4 error:&error] autorelease];
    
    NSParameterAssert(videoWriter);
    float bitRate = 76800.0f * 3.5f;
    //	float bitRate = 86800.0f * 8.0f;
	NSInteger frameInterval = 30;
    
    NSDictionary *compressionSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                         [NSNumber numberWithFloat:bitRate], AVVideoAverageBitRateKey,
                                         [NSNumber numberWithInteger:frameInterval], AVVideoMaxKeyFrameIntervalKey,
                                         nil];
    NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                   AVVideoCodecH264, AVVideoCodecKey,
                                   AVVideoScalingModeResizeAspectFill, AVVideoScalingModeKey,
                                   [NSNumber numberWithInt:320], AVVideoWidthKey,
                                   [NSNumber numberWithInt:240], AVVideoHeightKey,
                                   compressionSettings, AVVideoCompressionPropertiesKey
                                   ,nil];
    
    AVAssetWriterInput* videoWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings] retain];
    
    AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput sourcePixelBufferAttributes:nil];
    
    NSParameterAssert(videoWriterInput);
    NSParameterAssert([videoWriter canAddInput:videoWriterInput]);
    
    [videoWriter addInput:videoWriterInput];
    //Start a session:
    [videoWriter startWriting];
    [videoWriter startSessionAtSourceTime:kCMTimeZero];
    //Write some samples:
    CVPixelBufferRef buffer = NULL;
    
    int frameCount = 0;
    //    int averageFrame = 0.05*20;
    int averageFrame = 1;
    
    UIImage *img;

    for(NSData * imgData in imagesArray)
    {
        img = [[UIImage alloc]initWithData:imgData];
        
        buffer = [self pixelBufferFromCGImage:[img CGImage] andSize:size];
        [img release];
        img = nil;
        
        BOOL append_ok = NO;
        int j = 0;
        while (!append_ok && j < 30)
        {
            if (adaptor.assetWriterInput.readyForMoreMediaData)
            {
                CMTime frameTime = CMTimeMake(frameCount,(int32_t) fps);
                
                append_ok = [adaptor appendPixelBuffer:buffer withPresentationTime:frameTime];
            }
            j++;
        }
        CVBufferRelease(buffer);
          frameCount = frameCount + averageFrame;
    }
    [videoWriterInput markAsFinished];
    [videoWriter finishWritingWithCompletionHandler:
     ^(void ) {
         [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:0];
         NSLog(@"finishWriting...");
         [self CompileFilesToMakeMovie:path];
     }
     ];
}


//音乐+视频
-(void)CompileFilesToMakeMovie:(NSString *)_videoPath;
{
    NSString * mp3Path = [[NSBundle mainBundle]pathForResource:@"千千阙歌" ofType:@"mp3"];
    NSURL*    audio_inputFileUrl = [NSURL fileURLWithPath:mp3Path];
    
    NSURL*    video_inputFileUrl = [NSURL fileURLWithPath:_videoPath];
    
    NSURL*    outputFileUrl = [NSURL fileURLWithPath:_videoPath];
    
    AVMutableComposition* mixComposition = [AVMutableComposition composition];
    AVURLAsset* firstAsset = [[AVURLAsset alloc]initWithURL:video_inputFileUrl options:nil];
    AVMutableCompositionTrack *firstTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    [firstTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, firstAsset.duration) ofTrack:[[firstAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:kCMTimeZero error:nil];
    
    AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audio_inputFileUrl options:nil];
    CMTimeRange audio_timeRange = CMTimeRangeMake(kCMTimeZero, audioAsset.duration);
    AVMutableCompositionTrack *b_compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    
    
    int videoLength = firstAsset.duration.value/firstAsset.duration.timescale;
    int audioLength = audioAsset.duration.value/audioAsset.duration.timescale;
    
    if (videoLength >= audioLength)
    {
        float a = (videoLength*0.01) / (audioLength*0.01);

        [b_compositionAudioTrack insertTimeRange:audio_timeRange ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];

        for (int i = 1; i<(int)a; i++) {
            [b_compositionAudioTrack insertTimeRange:audio_timeRange ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:audioAsset.duration error:nil];
        }
        
        CMTime time = CMTimeMake(videoLength - audioLength*((int)a), 1);
        CMTime time1 = CMTimeMake(audioLength*((int)a), 1);
        
        [b_compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, time) ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:time1 error:nil];
    }
    else
    {
        [b_compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, firstAsset.duration) ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];
    }
    
    [firstAsset release];
    [audioAsset release];
    
    
    AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetMediumQuality];
    _assetExport.outputURL = outputFileUrl;
    _assetExport.outputFileType = AVFileTypeMPEG4;

    [_assetExport exportAsynchronouslyWithCompletionHandler:
     ^(void ) {
         NSLog(@"合成音视频");
         [_assetExport release];
     }
     ];
}
*/
@end
